import { computed, h, ref, watch } from 'vue';
import { useMenuStore } from '@/stores/menu-store';
import { Menu } from '@jecloud/ui';
import { collectStarMenu, openMenu } from '@/hooks/use-menu';
import { useInjectSiderMenu } from '../context';
import { debounce } from '@jecloud/utils';
export function useSiderMenuTree({ props }) {
  const menuStore = useMenuStore();
  const menus = computed(() => {
    const siderMenus = menuStore.getSiderMenusByTopMenu(props.root);
    return menuStore.init ? buildMenus(siderMenus) : [];
  });

  const siderMenu = useInjectSiderMenu();
  const openKeys = ref([]);
  const selectedKeys = ref([]);
  const animation = ref(false);
  const tempOpenKeys = ref([]);
  // 打开菜单
  const openMenus = (menuId) => {
    const menu = menuStore.getMenuById(menuId);
    const keys = menu?.path.split('/');
    // 点击顶部菜单时，左侧多级菜单，默认不展开
    if (menuStore.openAction === 'topMenuClick') {
      const siderMenus = menuStore.getSiderMenusByTopMenu(props.root);
      // 左侧多级菜单，默认不展开
      if (siderMenus?.length > 1) {
        openKeys.value = [];
        tempOpenKeys.value = [];
        return;
      }
    }
    openKeys.value = keys;
    tempOpenKeys.value = keys;
  };

  // 设置菜单选择和打开数据
  watch(
    () => menuStore.activeSiderMenu,
    () => {
      selectedKeys.value = [menuStore.activeSiderMenu];
      const menu = menuStore.getMenuById(menuStore.activeSiderMenu);
      // 激活顶部菜单，处理打开菜单
      const topMenu = menu?.topMenus?.find((menu) => menu.id === props.root);
      if (topMenu) {
        openMenus(menuStore.activeSiderMenu);
      }
    },
    { immediate: true },
  );
  const onOpenChange = (keys) => {
    if (keys.length > tempOpenKeys.value?.length) {
      const newOpenKey = keys.find((key) => !tempOpenKeys.value.includes(key));
      openMenus(newOpenKey);
    } else {
      tempOpenKeys.value = keys;
    }
  };
  // 增加角标动画效果
  const closeAnimation = debounce(() => {
    animation.value = false;
  }, 1000);
  watch(
    () => [siderMenu.isHover.value, siderMenu.collapsed.value],
    () => {
      // 关闭，未展开，增加动画效果
      if (siderMenu.collapsed.value && !siderMenu.isHover.value) {
        animation.value = true;
        closeAnimation();
      }
    },
  );

  // 打开菜单
  const clickMenu = ({ key }) => {
    openMenu(key);
  };
  return {
    menus,
    menuStore,
    openKeys,
    selectedKeys,
    animation,
    siderMenu,
    clickMenu,
    onOpenChange,
  };
}
/**
 * 构建标题
 * @param {*} item
 * @returns
 */
function buildTitle(item) {
  const menu = item.type === 'MENU';
  const menuStore = useMenuStore();
  const isStar = menuStore.starMenus.includes(item.id);
  return h('div', { class: 'menu-tree-body-menu-title' }, [
    h('span', { class: 'menu-tree-body-menu-title-content' }, item.text),
    h(
      'div',
      {
        class: 'menu-tree-body-menu-title-badge',
        style: { display: item.badge > 0 ? undefined : 'none' },
      },
      item.badge > 100 ? '99+' : item.badge,
    ),
    item.lock
      ? h('i', { class: ['menu-tree-body-menu-title-lock', 'fal fa-lock-alt'] })
      : h('i', {
          class: [
            'menu-tree-body-menu-title-star',
            { 'fas fa-star is--star': isStar, 'fal fa-star': !isStar },
          ],
          style: { display: menu ? 'none' : undefined },
          onClick(event) {
            event.stopPropagation();
            collectStarMenu(item.id);
          },
        }),
  ]);
}
/**
 * 构建菜单
 * @param {*} data
 * @returns
 */
function buildMenus(data = []) {
  return data.map((item) => {
    if (item.leaf) {
      return h(
        Menu.Item,
        { key: item.id, title: item.text, icon: item.icon },
        {
          default() {
            return buildTitle(item);
          },
        },
      );
    } else {
      return h(
        Menu.SubMenu,
        { key: item.id, icon: item.icon },
        {
          title() {
            return buildTitle(item);
          },
          default() {
            return buildMenus(item.children);
          },
        },
      );
    }
  });
}
